package com.lili.price;

/**
 * @Auther: 李 力
 * @Date: 2024/8/26
 * @Description: 714.买卖股票的最佳时机含手续费
 * @version: 1.0
 */
public class LeetCode714 {

    public static int maxProfit(int[] prices, int fee) {
        int[] buy = new int[prices.length];
        int[] sell = new int[prices.length];
        buy[0] = -prices[0];
        sell[0] = 0;
        for (int i = 1; i < prices.length; i++) {
            buy[i] = Math.max(buy[i - 1], sell[i - 1] - prices[i]);
            sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i] - fee);
        }
        return sell[prices.length - 1];
    }

    //优化如下:
    public static int maxProfit2(int[] prices, int fee) {
        int prevBuy = -prices[0];
        int prevSell = 0;
        for (int i = 1; i < prices.length; i++) {
            int buy = Math.max(prevBuy, prevSell - prices[i]);
            int sell = Math.max(prevSell, prevBuy + prices[i] - fee);
            prevBuy = buy;
            prevSell = sell;
        }
        return prevSell;
    }
}
